package com.lu.bio.client;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.lu.GlobalConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.concurrent.TimeUnit;

/**
 * @program lu-netty
 * @description:
 * @author: zhanglu
 * @create: 2022-06-09 15:07:00
 */
@Slf4j
public class BioClient {

    public static void main(String[] args) throws IOException {
        try {
            Socket socket = new Socket(GlobalConfig.LOCAL_IP, GlobalConfig.LOCAL_PORT);
            log.info("BioClient start...");
            BioClientHandler clientHandler = new BioClientHandler(socket, CharsetUtil.UTF_8);
            clientHandler.start();
            clientHandler.writeAndFlush("1");
            clientHandler.writeAndFlush("2");
            //等待服务端响应
            TimeUnit.SECONDS.sleep(4);
            clientHandler.ctx().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void server() throws Exception {
        ServerSocket serverSocket = new ServerSocket(8001);
        while (true){
            Socket socket = serverSocket.accept();
            new Thread(() -> {
                BufferedReader in = null;
                PrintWriter out = null;
                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out = new PrintWriter(socket.getOutputStream(), true);
                    while (true){
                        String res = in.readLine();
                        if(StrUtil.isNotEmpty(res)){
                            log.info("客户端消息：" + res);
                            out.write("收到");
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.close();
                        in.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    @Test
    public void client() throws IOException {
        Socket socket = new Socket(GlobalConfig.LOCAL_IP, GlobalConfig.LOCAL_PORT);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out.println("test");
        while (true){
            String res = in.readLine();
            if(StrUtil.isNotEmpty(res)){
                log.info("服务端消息：" + res);
                break;
            }
        }
        in.close();
        out.close();
        socket.close();
    }

}
